package com.winning.ds.role.controller;

import com.winning.ds.common.controller.BaseController;
import com.winning.ds.common.util.ResponseEntity;
import com.winning.ds.common.util.UUIDUtils;
import com.winning.ds.role.entity.AppEntity;
import com.winning.ds.role.entity.SjqxEntity;
import com.winning.ds.role.service.AppService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
import java.util.Random;

/** @Author: lxd@winning.com.cn @Description: 应用注册模块 @Date: 2018-07-24 10:50:08 */
@Slf4j
@RestController
@RequestMapping("/application")
public class AppController extends BaseController {

  @Autowired private AppService appService;

    @Value("${spring.application.yydm:DQMT}")
  private String YYDM;

    /**
     *获取验证码
     */
    @RequestMapping(value = "/getVerifyCode",method = RequestMethod.GET)
    public ResponseEntity getVerifyCode(HttpServletRequest request){
        // 验证码字符个数
        int codeCount = 4;
        char[] codeSequence = { 'r', 'Q', '4', 'S', '6', 'w', 'u', 'D','a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k','m', 'n', 'p', 'q', '2', 's', 't', '8', 'v', '7',
                'x', 'y', 'z', 'A', 'B', 'C', '9', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', '3', 'R', '5', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};

        // 创建一个随机数生成器类
        Random random = new Random();
        // randomCode用于保存随机产生的验证码，以便用户登录后进行验证。
        StringBuffer randomCode = new StringBuffer();
        for (int i = 0; i < codeCount; i++) {
            // 得到随机产生的验证码数字。
            String strRand = String.valueOf(codeSequence[random.nextInt(55)]);
            // 将产生的四个随机数组合在一起。
            randomCode.append(strRand);
        }
      String verifycode = randomCode.toString();
      //生成验证码需要存储和sessionid绑定
      HttpSession session = request.getSession();
      String sessionId = session.getId();
      if(StringUtils.isEmpty(sessionId)){
          return ResponseEntity.error(10001,"未获取到sessionId");
      }
      session.setAttribute(sessionId,verifycode);
      return ResponseEntity.ok().put("verifycode",verifycode);
    }
  /**
   * 查询应用列表
   *
   * @param queryParams
   * @return ResponseEntity
   */
  @RequestMapping(value = "/applist", method = RequestMethod.POST)
  public ResponseEntity queryAppList(
      HttpServletRequest request, @RequestParam Map<String, Object> queryParams) {
    List<AppEntity> list = appService.queryAppList(queryParams);
    return ResponseEntity.ok().put("list", list);
  }

  /**
   * 根据应用代码查询应用信息
   *
   * @param yydm
   * @return ResponseEntity
   */
  @RequestMapping(value = "/queryApp/{yydm}", method = RequestMethod.GET)
  public ResponseEntity queryApp(HttpServletRequest request, @PathVariable String yydm) {
    AppEntity app = appService.queryApp(yydm);
    return ResponseEntity.ok().put("app", app);
  }

    /**
     * 根据配置应用代码查询应用信息
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/queryApp", method = RequestMethod.GET)
    public ResponseEntity queryApp(HttpServletRequest request) {
        AppEntity app = appService.queryApp(YYDM);
        return ResponseEntity.ok().put("app", app);
    }

  /**
   * 保存应用注册
   *
   * @param request the request
   * @param app the app
   * @return ResponseEntity the response entity
   */
  @RequestMapping(value = "/save", method = RequestMethod.POST)
  public ResponseEntity save(HttpServletRequest request, @RequestBody AppEntity app) {
    log.info("save begin: app : {}", app);
    long startTime = System.currentTimeMillis();
    try {
      AppEntity appEntity = appService.queryApp(app.getYydm());

      if (appEntity != null && StringUtils.isNotEmpty(appEntity.getYydm())) {
        return ResponseEntity.error(500, "应用代码已存在");
      }
      app.setMgorder("0");
      appService.save(app);
      return ResponseEntity.ok().put("yydm", app.getYydm());
    } catch (Exception exception) {
      log.error("save failed!", exception);
      throw exception;
    } finally {
      log.info("save end, use time {} ms", System.currentTimeMillis() - startTime);
    }
  }

  /**
   * 更新
   *
   * @param app
   * @return ResponseEntity
   */
  @RequestMapping(value = "/update", method = RequestMethod.POST)
  public ResponseEntity update(HttpServletRequest request, @RequestBody AppEntity app) {
    // ValidatorUtils.validateEntity(user);
    appService.update(app);
    return ResponseEntity.ok().put("yydm", app.getYydm());
  }

  /**
   * 删除角色
   *
   * @param yydm
   * @return
   */
  @RequestMapping(value = "/delApp/{yydm}", method = RequestMethod.DELETE)
  public ResponseEntity delApp(HttpServletRequest request, @PathVariable String yydm) {
    appService.delApp(yydm);
    return ResponseEntity.ok();
  }
  /**
   * 启用角色
   *
   * @param yydm
   * @return
   */
  @RequestMapping(value = "/doEnable/{yydm}", method = RequestMethod.DELETE)
  public ResponseEntity doEnable(HttpServletRequest request, @PathVariable String yydm) {
    appService.doEnable(yydm);
    return ResponseEntity.ok();
  }

  /** 根据应用代码获取数据权限 */
  @RequestMapping(value = "/querySjqx", method = RequestMethod.POST)
  public ResponseEntity querySjqx(
      HttpServletRequest request, @RequestParam Map<String, Object> queryParams) {
    queryParams.put("jlzt", "0");
    List<SjqxEntity> sjqx = appService.querySjqx(queryParams);
    return ResponseEntity.ok().put("sjqx", sjqx);
  }

  /** 保存数据权限 */
  @RequestMapping(value = "/saveSjqx", method = RequestMethod.POST)
  public ResponseEntity saveSjqx(HttpServletRequest request, @RequestBody SjqxEntity sjqx) {
    // ValidatorUtils.validateEntity(user);
    sjqx.setSjdm(UUIDUtils.getUUID());
    sjqx.setJlzt("0");
    sjqx.setMgorder("0");
    appService.saveSjqx(sjqx);
    return ResponseEntity.ok().put("sjdm", sjqx.getSjdm());
  }

  /**
   * 更新数据权限
   *
   * @param sjqx
   * @return ResponseEntity
   */
  @RequestMapping(value = "/updateSjqx", method = RequestMethod.POST)
  public ResponseEntity updateSjqx(HttpServletRequest request, @RequestBody SjqxEntity sjqx) {
    // ValidatorUtils.validateEntity(user);
    appService.updateSjqx(sjqx);
    return ResponseEntity.ok().put("sjdm", sjqx.getSjdm());
  }

  /**
   * 删除数据权限
   *
   * @param sjdm
   * @return
   */
  @RequestMapping(value = "/delSjqx/{sjdm}", method = RequestMethod.DELETE)
  public ResponseEntity deleteSjqx(HttpServletRequest request, @PathVariable String sjdm) {
    appService.deleteSjqx(sjdm);
    return ResponseEntity.ok();
  }

  /** 根据应用代码查询应用logo信息 */
  @RequestMapping(value = "/queryLogo/{yydm}", method = RequestMethod.GET)
  public void queryLogo(
      HttpServletRequest request, HttpServletResponse response, @PathVariable String yydm) {

    byte[] fileByte = appService.getFileLogo();
    OutputStream toClient = null;

    try {
      // 重置response
      response.reset();
      response.setContentType("bin");
      toClient = new BufferedOutputStream(response.getOutputStream());
      response.setContentType("application/octet-stream");
      response.addHeader("Content-Disposition", "attachment;filename=logo.ico");
      response.addHeader("Content-Length", "" + fileByte.length);
      response.getOutputStream().write(fileByte);
      toClient.write(fileByte);
      toClient.flush();
      toClient.close();
    } catch (Exception e) {
      if (toClient != null) {
        try {
          toClient.flush();
          toClient.close();
        } catch (Exception ee) {
        }
      }
    }
  }

  /** 根据应用代码查询应用logo信息 */
  @RequestMapping(value = "/queryLoginLogo/{yydm}", method = RequestMethod.GET)
  public void queryLoginLogo(
      HttpServletRequest request, HttpServletResponse response, @PathVariable String yydm) {

    byte[] fileByte = appService.queryLoginLogo();
    OutputStream toClient = null;

    try {
      response.reset();
      response.setContentType("bin");
      toClient = new BufferedOutputStream(response.getOutputStream());
      response.setContentType("application/octet-stream");
      response.addHeader("Content-Disposition", "attachment;filename=logo.ico");
      response.addHeader("Content-Length", "" + fileByte.length);
      response.getOutputStream().write(fileByte);
      toClient.write(fileByte);
      toClient.flush();
      toClient.close();
    } catch (Exception e) {
      if (toClient != null) {
        try {
          toClient.flush();
          toClient.close();
        } catch (Exception ee) {
        }
      }
    }
  }

  /** 根据应用代码查询应用logo信息 */
  @RequestMapping(value = "/queryTitleLogo/{yydm}", method = RequestMethod.GET)
  public void queryTitleLogo(
      HttpServletRequest request, HttpServletResponse response, @PathVariable String yydm) {

    byte[] fileByte = appService.queryTitleLogo();
    OutputStream toClient = null;

    try {
      response.reset();
      response.setContentType("bin");
      toClient = new BufferedOutputStream(response.getOutputStream());
      response.setContentType("application/octet-stream");
      response.addHeader("Content-Disposition", "attachment;filename=logo.ico");
      response.addHeader("Content-Length", "" + fileByte.length);
      response.getOutputStream().write(fileByte);
      toClient.write(fileByte);
      toClient.flush();
      toClient.close();
    } catch (Exception e) {
      if (toClient != null) {
        try {
          toClient.flush();
          toClient.close();
        } catch (Exception ee) {
        }
      }
    }
  }

  /**
   * 批量更新功能按钮
   *
   * @return ResponseEntity
   */
  @RequestMapping(value = "/updateYysjList", method = RequestMethod.POST)
  public ResponseEntity updateYysjList(@RequestBody List<SjqxEntity> GnanList) {
    for (SjqxEntity sgge : GnanList) {
      appService.updateSjqx(sgge);
    }
    return ResponseEntity.ok();
  }

  /**
   * 批量更新应用排列顺序
   *
   * @return ResponseEntity
   */
  @RequestMapping(value = "/updateYyzcList", method = RequestMethod.POST)
  public ResponseEntity updateYyzcList(@RequestBody List<AppEntity> appList) {

    for (AppEntity appEntity : appList) {
      appService.update(appEntity);
    }
    return ResponseEntity.ok();
  }
}
